package com.xavier.dong.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author XavierDong
 **/
public class GroupChatClient {

    // 定义相关的属性
    private final String host = "127.0.0.1";  // 服务器ip

    private final int port = 6667; // 服务器端口

    private Selector selector;

    private SocketChannel socketChannel;

    private String username;

    public GroupChatClient() {

        // 初始化工作
        try {
            this.selector = Selector.open();
            this.socketChannel = SocketChannel.open(new InetSocketAddress(this.host, this.port));
            // 设置 非 阻塞
            this.socketChannel.configureBlocking(false);

            // 将 SocketChannel 注册到 Selector 上
            this.socketChannel.register(this.selector, SelectionKey.OP_READ);

            // 得到 username
            this.username = this.socketChannel.getLocalAddress().toString().substring(1);

            System.out.println(this.username + " is ok.....");

        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    // 向服务器 发送消息
    private void sendInfo(String msg) {

        msg = this.username + " 说： " + msg;

        try {
            this.socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    // 读取 从 服务端 回送的消息
    private void readInfo() {

        try {
            int readChannels = this.selector.select();

            if (readChannels > 0) {
                // 有可用的通道
                Iterator<SelectionKey> selectionKeyIterator = this.selector.selectedKeys().iterator();

                while (selectionKeyIterator.hasNext()) {
                    SelectionKey selectionKey = selectionKeyIterator.next();

                    if (selectionKey.isReadable()) {
                        // 得到相关的通道
                        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();

                        // 得到一个 Buffer
                        ByteBuffer buffer = ByteBuffer.allocate(1024);

                        socketChannel.read(buffer);
                        // 读到的 缓冲区数据 转成 字符串
                        String str = new String(buffer.array());
                        System.out.println(str.trim());

                    }
                }

                // 删除 当前的 SelectionKey 防止 重复操作
                selectionKeyIterator.remove();

            } else {

//                System.out.println("没有 可用的通道.");

            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {

        // 启动 客户端
        GroupChatClient groupChatClient = new GroupChatClient();

        // 启动线程
        ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);

        // 启动 线程 每隔 3秒 ，读取从 服务端 发送的数据
        executorService.execute(() -> {
            while (true) {

                groupChatClient.readInfo();

                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        });

        // 发送 数据 到 服务器端
        Scanner scanner = new Scanner(System.in);

        while (scanner.hasNextLine()) {
            String nextLine = scanner.nextLine();
            groupChatClient.sendInfo(nextLine);
        }

    }
}
